﻿using System;
using System.Data;
using System.Collections.Generic;
using CrazyTalk.Caching;
using CrazyTalk.DALFactory;
using CrazyTalk.IDAL;
using CrazyTalk.Models;
namespace CrazyTalk.BLL
{
    /// <summary>
    /// PermissionListBLL
    /// </summary>
    public class PermissionBLL
    {
        private static PermissionBLL _instance;
        private static readonly object SyncLock = new object();
        public static PermissionBLL Instance
        {
            get
            {
                lock (SyncLock)
                {
                    if (_instance == null)
                    {
                        _instance = new PermissionBLL();
                    }
                }
                return _instance;
            }
        }
        private readonly IPermissionDAL _dal = DataAccess.Get<IPermissionDAL>();
        /// <summary>
        /// 根据输入的用户名和角色编号，获取用户的权限列表
        /// </summary>
        /// <param name="userId">用户名</param>
        /// <param name="roleId">角色编号</param>
        /// <returns></returns>
        public DataTable GetPermissionList(string userId, int roleId)
        {
            return _dal.GetPermissionList(userId, roleId);
        }
        /// <summary>
        /// 从缓存获取用户的显示菜单列表
        /// </summary>
        public List<Permission> GetPermissionListByCache(string userId, int roleId)
        {
            DefaultCache cache = DefaultCache.GetCacheService();
            string cacheKey = CacheKeys.Permission_List_User + userId;
            List<Permission> list = cache.RetrieveObject(cacheKey) as List<Permission>;
            if (list == null)
            {
                DataTable dtb = _dal.GetPermissionList(userId, roleId);
                if (dtb == null || dtb.Rows.Count == 0)
                {
                    return null;
                }
                list = new List<Permission>();
                foreach (DataRow item in dtb.Rows)
                {
                    list.Add(new Permission { MenuID = Convert.ToInt32(item["MenuID"]), Type = Convert.ToInt16(item["Type"]) });
                }
                cache.AddObject(cacheKey, list);
            }
            return list;
        }
        /// <summary>
        /// 得到最大ID
        /// </summary>
        public int GetMaxId()
        {
            return _dal.GetMaxId();
        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int roleId, string menuID, int funcID)
        {
            return _dal.Exists(roleId, menuID, funcID);
        }
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Add(Permission model)
        {
            return _dal.Add(model);
        }
        /// <summary>
        /// 批量增加数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int AddList(List<Permission> list)
        {
            return _dal.AddList(list);
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Permission model)
        {
            return _dal.Update(model);
        }
        /// <summary>
        /// 网吧连锁机构批量处理子角色的权限的方法
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int UpdateList(List<Permission> list)
        {
            return _dal.UpdateList(list);
        }
        /// 网吧连锁机构批量处理子角色的权限的方法
        //表PermissionList添加了字段PUserId后的修改
        public int UpdateList2(List<Permission> list)
        {
            return _dal.UpdateList2(list);
        }
        /// <summary>
        /// 更新权限控制
        /// </summary>
        /// <param name="lsNewValue">新增权限值列</param>
        /// <param name="lsDelValue">删除权限值列</param>
        /// <param name="roleId">涉及角色编号</param>
        /// <returns></returns>
        public bool UpdatePermission(List<string> lsNewValue, List<string> lsDelValue, int roleId)
        {
            bool result = _dal.UpdatePermission(lsNewValue, lsDelValue, roleId);
            if (result)
                ReLoadCache(roleId);
            return result;
        }
        /// <summary>
        /// 更新权限控制(添加了PUserId的控制限制)
        /// </summary>
        /// <param name="lsNewValue">新增权限值列</param>
        /// <param name="lsDelValue">删除权限值列</param>
        /// <param name="roleId">涉及角色编号</param>
        /// <returns></returns>
        public bool UpdatePermission2(List<string> lsNewValue, List<string> lsDelValue, int roleId)
        {
            bool result = _dal.UpdatePermission2(lsNewValue, lsDelValue, roleId);
            if (result)
                ReLoadCache(roleId);
            return result;
        }
        /// <summary>
        /// 重载指定角色权限缓存
        /// </summary>
        /// <param name="roleId"></param>
        public void ReLoadCache(int roleId)
        {
            DefaultCache cache = DefaultCache.GetCacheService();
            string cacheKey = CacheKeys.Permiss_Permisslist_r + roleId; //"/User/UserInfo/_" + userId;
            var list = GetModelList(roleId);
            if (list != null)
            {
                cache.AddObject(cacheKey, list);
            }
            else
            {
                cache.RemoveObject(cacheKey);
            }
        }
        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int roleId, string menuID, int funcID)
        {
            return _dal.Delete(roleId, menuID, funcID);
        }
        /// <summary>
        /// 删除一条数据(带有约束条件)
        /// </summary>
        public bool Delete(List<string> fields, List<object> values)
        {
            return _dal.Delete(fields, values);
        }
        /// <summary>
        /// 删除一条数据(带有约束条件)
        /// </summary>
        public bool DeleteUnionMenu(List<string> fields, List<object> values)
        {
            return _dal.DeleteUnionMenu(fields, values);
        }
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Permission GetModel(int roleId, string menuID, int funcID)
        {
            return _dal.GetModel(roleId, menuID, funcID);
        }
        /// <summary>
        /// 得到一个对象实体，从缓存中
        /// </summary>
        public Permission GetModelByCache(int roleId, string menuID, int funcID)
        {
            DefaultCache cacheService = DefaultCache.GetCacheService();
            string xpath = CacheKeys.PermissionModelKey + roleId + menuID + funcID ;
            Permission model = cacheService.RetrieveObject(xpath) as Permission;
            if (model == null)
            {
                model = _dal.GetModel(roleId, menuID, funcID);
                if (model != null)
                {
                    cacheService.AddObject(xpath, model);
                }
            }
            return model;
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(List<string> fields, List<object> values)
        {
            return _dal.GetList(fields, values);
        }
        /// <summary>
        /// 网吧连锁给下级设置权限提取权限时用。
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public DataSet GetListUnionMenu1(List<string> fields, List<object> values)
        {
            return _dal.GetListUnionMenu1(fields, values);
        }
        /// <summary>
        /// 网吧连锁给下级设置权限提取权限时用。(后期改进型，添加了PUserId字段)
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public DataSet GetListUnionMenu2(List<string> fields, List<object> values)
        {
            return _dal.GetListUnionMenu2(fields, values);
        }
        //主页快捷菜单专用
        public DataSet GetListUnionMenu(List<string> fields, List<object> values, List<string> list)
        {
            return _dal.GetListUnionMenu(fields, values, list);
        }
        //主页快捷菜单专用（表permissionList添加了字段PUserId后的修改）
        public DataSet GetListUnionMenu2(List<string> fields, List<object> values, List<string> list, string parentId)
        {
            return _dal.GetListUnionMenu2(fields, values, list, parentId);
        }
        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(int top, List<string> fields, List<object> values, string filedOrder)
        {
            return _dal.GetList(top, fields, values, filedOrder);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Permission> GetModelList(List<string> fields, List<object> values)
        {
            DataSet ds = _dal.GetList(fields, values);
            return DataTableToList(ds.Tables[0]);
        }
        /// <summary>
        /// 从缓存中获取权限数据列表
        /// </summary>
        public List<Permission> GetModelListByCache(int roleId)
        {
            DefaultCache cache = DefaultCache.GetCacheService();
            string cacheKey = CacheKeys.Permiss_Permisslist_r + roleId;
            var list = cache.RetrieveObject(cacheKey) as List<Permission>;
            if (list == null)
            {
                list = GetModelList(roleId);
                if (list != null)
                {
                    cache.AddObject(cacheKey, list);
                }
            }
            return list;
        }
        /// <summary>
        /// 通过角色编号从数据库获取数据实体列表
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<Permission> GetModelList(int roleId)
        {
            List<string> fields = new List<string> { "RoleId" };
            List<object> values = new List<object> { roleId };
            return GetModelList(fields, values);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Permission> DataTableToList(DataTable dt)
        {
            List<Permission> modelList = new List<Permission>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                Permission model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = new Permission();
                    modelList.Add(model);
                }
            }
            return modelList;
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetAllList()
        {
            return GetList(null, null);
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public int GetRecordCount(List<string> fields, List<object> values)
        {
            return _dal.GetRecordCount(fields, values);
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetListByPage(List<string> fields, List<object> values, string orderby, int startIndex, int endIndex)
        {
            return _dal.GetListByPage(fields, values, orderby, startIndex, endIndex);
        }
    }
}
